﻿using System;
using System.Windows.Forms;
using WorkLogger.Client.Controls;
using WorkLogger.Client.DataAccess.Repository;
using WorkLogger.Client.Forms;

namespace WorkLogger.Client.Presenters {
	public class MainMenuPresenter {
		private readonly AppOptions appOptions;
		private readonly IWorkDayRepository workDayRepository;
		private readonly ISystemClock systemClock;
		private readonly WorkTimeCalculator workTimeCalculator;
		public event EventHandler OptionsChanged;

		public MainMenuPresenter(IMainMenuView mainMenuView,
		                         AppOptions appOptions,
		                         IWorkDayRepository workDayRepository,
		                         ISystemClock systemClock,
		                         WorkTimeCalculator workTimeCalculator) {
			this.appOptions = appOptions;
			this.workDayRepository = workDayRepository;
			this.systemClock = systemClock;
			this.workTimeCalculator = workTimeCalculator;
			mainMenuView.AboutProgram += MainMenuViewAboutProgram;
			mainMenuView.OptionsClick += MainMenuViewOptionsClick;
			mainMenuView.WorkedTimeReport += MainMenuViewWorkedTimeReport;
			mainMenuView.Exit += MainMenuViewExit;
		}

		private static void MainMenuViewExit(object sender, EventArgs e) {
			if (MessageBox.Show("Вы действительно хотите выйти?", "Выход", MessageBoxButtons.YesNo) == DialogResult.Yes) {
				Application.Exit();
			}
		}

		private void MainMenuViewWorkedTimeReport(object sender, EventArgs e) {
			using (var form = new WorkedTimeReportForm()) {
				form.Salary = appOptions.Salary;
				form.DeductIncomeTax = appOptions.DeductIncomeTax;
				var presenter = new WorkedTimeReportPresenter(form, workDayRepository, systemClock, workTimeCalculator, appOptions);
				presenter.BuildMonthReport();
				form.ShowDialog();
			}
		}

		private void MainMenuViewOptionsClick(object sender, EventArgs e) {
			using (var form = new OptionsForm()) {
				form.CoffeeBreak = appOptions.CoffeeBreak;
				form.Salary = appOptions.Salary;
				form.WorkDayDuration = appOptions.WorkDayDuration.GetTimeSpan();
				form.DeductIncomeTax = appOptions.DeductIncomeTax;
				form.ProgramPath = AppOptions.ProgramPath;

				if (form.ShowDialog() == DialogResult.OK) {
					appOptions.CoffeeBreak = form.CoffeeBreak;
					appOptions.Salary = form.Salary;
					appOptions.WorkDayDuration = new TimeSpanXml(form.WorkDayDuration);
					appOptions.DeductIncomeTax = form.DeductIncomeTax;
					AppOptions.Save(appOptions);

					if (OptionsChanged != null)
						OptionsChanged(this, e);
				}
			}
		}

		private static void MainMenuViewAboutProgram(object sender, EventArgs e) {
			using (var form = new AboutProgramForm()) {
				form.ShowDialog();
			}
		}
	}
}